<template>
  <div class="order-actions">
    <!-- <van-dialog v-model="confirmPickupDialogVisible" title="确认收货" show-cancel-button>
         <template #default>确认收货后，订单交易完成，欠款将立即到达商家账户。</template>
     </van-dialog>-->
    <van-button round plain size="small" v-if="showRefunds" @click="handleRefunds">批量退款</van-button>
    <van-button round plain size="small" v-if="showTryAgainButton" @click="handleTryAgain">再来一单</van-button>
    <van-button round plain size="small" v-if="showQueryShipment" @click="handleQueryShipment">查看物流</van-button>
    <van-button round plain size="small" type="primary" v-if="showConfirmReceipt"
                :loading="confirmPickupLoading" @click="handleConfirmReceipt">
      确认收货
    </van-button>
    <van-button round plain size="small" type="primary" v-if="showReview" :to="'/orders/' + order.id + '/reviews/new'">立即评价</van-button>
    <!--<van-button round plain size="small" v-if="showChangeButton">修改订单</van-button>-->
    <van-button round plain size="small" v-if="showCancelButton" @click="handleCancel" :loading="cancelLoading">取消订单</van-button>
    <van-button round size="small" type="primary" v-if="showPayButton" @click="handlePay">去支付</van-button>
  </div>
</template>

<script>
import * as _ from "lodash"
import { cart, message, order, security } from "@mall/api-services"
import { Button, Dialog, Toast } from "vant"
import {
  isAwaitingFulfillment,
  isAwaitingPayment,
  isAwaitingPickup,
  isCancelled,
  isClosed,
  isCompleted,
  isDeclined,
  isPartiallyShipped,
  isShipped,
} from "@/utils/order"

export default {
  name: "OrderActions",
  components: {
    [Button.name]: Button,
    [Dialog.name]: Dialog,
  },
  props: {
    order: order.Order,
  },
  computed: {
    orderStatus() {
      return this.order.status
    },
    reviewStatus() {
      return this.order.reviewStatus
    },
    showReview() {
      const { orderStatus, reviewStatus } = this
      return isCompleted(orderStatus) && reviewStatus !== order.OrderStatus.Reviewed
    },
    showConfirmReceipt() {
      const { orderStatus } = this
      return isAwaitingPickup(orderStatus) || isShipped(orderStatus)
    },
    showQueryShipment() {
      const { orderStatus } = this
      return !isAwaitingPayment(orderStatus) && !isAwaitingFulfillment(orderStatus) && !isCancelled(orderStatus) && !isDeclined(orderStatus)
    },
    showRefunds() {
      const { orderStatus } = this
      return !isAwaitingPayment(orderStatus) && !isCancelled(orderStatus) && !isClosed(orderStatus) && !isDeclined(orderStatus)
    },
    showTryAgainButton() {
      const { orderStatus } = this
      return isAwaitingFulfillment(orderStatus) || isAwaitingPickup(orderStatus)
          || isShipped(orderStatus) || isPartiallyShipped(orderStatus)
          || isCompleted(orderStatus) || isCancelled(orderStatus)
          || isClosed(orderStatus) || isDeclined(orderStatus)
    },
    showChangeButton() {
      const { orderStatus } = this
      return isAwaitingPayment(orderStatus)
    },
    showCancelButton() {
      const { orderStatus } = this
      return isAwaitingPayment(orderStatus)
    },
    showPayButton() {
      const { orderStatus } = this
      return isAwaitingPayment(orderStatus)
    },
  },
  data() {
    return {
      confirmPickupDialogVisible: false,
      confirmPickupLoading: false,
      cancelLoading: false,
    }
  },
  methods: {
    handleTryAgain() {
      const { order: aOrder } = this
      const { items } = aOrder
      const cartItems = _.map(items, item => _.assign(new cart.CartItem(), {
        productId: item.productId,
        variantId: item.variantId,
        quantity: item.quantity,
        checked: true,
      }))
      const customerId = security.SecurityUserHolder.getUserId()
      Toast.loading()
      cart.CartServiceV1.addCartItems(customerId, cartItems)
          .then(() => this.$router.push(`/cart`))
          .finally(() => Toast.clear())
    },
    handleQueryShipment() {
      const { order: aOrder } = this
      this.$router.push(`/orders/${aOrder.id}/shipments`)
    },
    handleRefunds() {
      const { order: aOrder } = this
      this.$router.push(`/orders/${aOrder.id}/refunds`)
    },
    handleConfirmReceipt() {
      const { order: aOrder } = this
      this.$dialog
          .confirm({
            title: "确认收货",
            message: "确认收货后，订单交易完成，欠款将立即到达商家账户。",
          })
          .then(() => {
            this.confirmPickupLoading = true
            order.OrderServiceV1
                .receiptOrder(aOrder.id)
                .then(() => this.confirmPickupLoading = false)
                .then(() => this.$emit("receipt"))
                .catch(({ response }) => {
                  Toast(message.getResponseMessage(response))
                  this.confirmPickupLoading = false
                })
          })
    },
    handleCancel() {
      const { order: aOrder } = this
      this.$dialog
          .confirm({
            confirmButtonText: "再考虑下",
            cancelButtonText: "取消订单",
            message: "订单还未付款，确定要取消吗？",
          })
          .catch(() => {
            this.cancelLoading = true
            order.OrderServiceV1.cancelOrder(aOrder.id, undefined)
                .then(() => this.cancelLoading = false)
                .then(() => this.$emit("cancel"))
                .catch(({ response }) => {
                  Toast(message.getResponseMessage(response))
                  this.cancelLoading = false
                })
          })
    },
    handlePay() {
      const { order: aOrder } = this
      const { id, totalAmount } = aOrder
      this.$router.push({
        path: `/payments`,
        query: {
          total_amount: totalAmount,
          order_ids: id,
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.order-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;

  .van-button {
    margin-left: 9px;
    width: 80px;
  }
}
</style>
